<template>
  <div class="edit-dialog">
    <el-dialog
      v-model="dialog"
      :title="titleName"
      :visible.sync="dialog"
      :close-on-click-modal="false"
      :show-close="false"
      width="460px"
      center
    >
      <el-form :model="addFormData" :rules="rules" ref="formRef" label-position="right" label-width="auto">
        <el-form-item label="设备列表" prop="deviceList">
          <el-select
            filterable
            v-model="addFormData.deviceList"
            multiple
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in options"
              :key="item.deviceId"
              :label="item.name"
              :value="item.deviceId"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" :loading="submitLoading" icon="el-icon-check" @click="submit('formRef')">提 交</el-button>
          <el-button icon="el-icon-close" @click="handleClose">取 消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import {listAllDevice} from "@/api/deviceManage";
  import {addDevice} from "@/api/platformManage";

  export default {
    name: "addDevice",
    props: {
      formData: Object,
      showDialog: Boolean,
      editType: Number,
    },
    data() {
      return {
        addFormData: {
          platformId: "",
          deviceList: "",
        },
        titleName: "添加设备",
        submitLoading: false,
        options: [],
        rules: {
          deviceList: [{required: true, message: "请选择设备", trigger: "blur"}]
        }
      };
    },
    mounted() {
      this.addFormData.platformId = this.$route.query.platformId;
      listAllDevice().then((res) => {
        this.options = res.value;
      });
    },
    computed: {
      dialog: function () {
        return this.showDialog;
      },
    },
    methods: {
      // 取消事件
      handleClose() {
        this.$emit("changeVisible", false);
      },
      submit(formName) {
        this.submitLoading = true;
        this.$refs[formName].validate(valid => {
          if (valid) {
            const that = this;
            const data = {
              ...that.addFormData
            };
            addDevice(data)
              .then((res) => {
                that.submitLoading = false;
                if (res["code"] == 200) {
                  that.$emit("changeVisible", false);
                  that.$emit("getList");
                  that.$message.success("添加成功!");
                } else {
                  that.$message(res["msg"]);
                }
              })
              .catch(() => {
                that.submitLoading = false;
              });
          } else {
            this.submitLoading = false;
            return false;
          }
        });
      },
    },
  };
</script>

<style>

</style>
